import axios from 'axios'
import router from '../router'
import { ElMessage } from 'element-plus'
import store from '../store'

// 检查token是否有效
export const checkTokenValidity = async () => {
  const token = localStorage.getItem('token')
  
  if (!token) {
    return false
  }
  
  try {
    // 尝试进行一次验证请求
    const response = await axios.get('/adminapi/user/verify-token')
    return response.data.valid === true
  } catch (error) {
    if (error.response && error.response.status === 401) {
      // token已失效，清除用户信息
      store.commit("clearUserInfo")
      localStorage.removeItem("token")
      
      ElMessage.warning({
        message: '登录已过期，请重新登录',
        duration: 3000
      })
      
      router.push("/login")
    }
    return false
  }
}

// 尝试刷新token
export const refreshToken = async () => {
  try {
    const response = await axios.post('/adminapi/user/refresh-token')
    if (response.data.ActionType === "OK") {
      // 保存新token
      const newToken = response.data.token
      localStorage.setItem('token', newToken)
      return true
    }
    return false
  } catch (error) {
    console.error('刷新token失败:', error)
    return false
  }
}

// 登出
export const logout = () => {
  store.commit("clearUserInfo")
  localStorage.removeItem("token")
  router.push("/login")
} 